package com.wl.employee.dao;

import com.wl.employee.entity.Employee;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

    @Resource
    private SessionFactory sessionFactory;

    @Override
    public void addEmployee(Employee employee) {
        this.sessionFactory.getCurrentSession().save(employee);
    }

    @Override
    public void editEmployee(Employee employee) {
        Session session = this.sessionFactory.getCurrentSession();
        String hql = "update Employee e set e.ename = ?, e.sex = ?, e.birthday = ?, e.joinDate = ?, e.editDate = ?, e.eno = ? where e.id = ?";
        Query query = session.createQuery(hql);
        query.setParameter(0, employee.getEname());
        query.setParameter(1, employee.getSex());
        query.setParameter(2, employee.getBirthday());
        query.setParameter(3, employee.getJoinDate());
        query.setParameter(4, employee.getEditDate());
        query.setParameter(5, employee.getEno());
        query.setParameter(6, employee.getId());
        query.executeUpdate();
    }

    @Override
    public void deleteEmployee(Employee employee) {
        this.sessionFactory.getCurrentSession().delete(employee);
    }

    @Override
    public List<Employee> findAll() {
        List list = this.sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
        return list;
    }

    @Override
    public Employee findById(Integer id) {
        return (Employee) this.sessionFactory.getCurrentSession().createQuery("from Employee where id=" + id).uniqueResult();
    }
}